<?php declare(strict_types=1);


namespace PinWuYun\domain\service\starLinkServer;

use Exception;

/**
 * 回调服务
 * Class CallBack
 * @package app\starLinkServer
 */
class CallBack extends Common
{
    /**
     * 具体逻辑
     * @param array $params 请求参数
     * @return mixed|string
     * @throws Exception
     */
    public function run(array $params): string
    {
        // 签名验证
        $this->checkSign($params);
        // 判断订单状态
        return $this->transformStatus((int)($params['updateType'] ?? 999), (string)($params['oldStatus'] ?? 999), (string)($params['newStatus'] ?? 999));
    }

    /**
     * 检测签名是否正确
     * @param array $params
     * @throws Exception
     */
    public function checkSign(array $params): void
    {
        $toBeSign = $params['sign'] ?? '';
        $this->initZero([0]);
        $sign = $this->geneSign($params);
        if($toBeSign != $sign) {
           throw new Exception('sign error', 10000);
        }
    }

    /**
     * 确定订单状态
     * @param int $updateType
     * @param string $oldStatus
     * @param string $newStatus
     * @return mixed|string
     */
    public function transformStatus(int $updateType, string $oldStatus, string $newStatus): string
    {
        $status = [
            // 第一类
            1 => [
                // 已支付待发货 => 已发货待收货
                '20' => [
                    '30' => Config::CONFIRMED_RECEIVE
                ],
                // 30	已发货待收货	40	交易成功
                '30' => [
                    '40' => Config::TRADE_FINISH
                ],
            ],
            // 第二类
            2 => [
                // 1	供应商审核中	7	供应商审核通过(退款成功)
                '1' => [
                    '7' => '供应商审核通过(退款成功)',
                    '10' => '退款关闭',
                    '3' => '供应商审核通过(待买家发货)',
                ],
                '3' => [
                    '4' => '买家发货待供应商确认收货',
                    '10' => '退货关闭',
                ],
                '4' => [
                    '7' => '退货成功',
                    '3' => '供应商审核(拒绝收货)，待买家发货',
                ],

            ],
            // 第三类
            3 => [
                '30' => [
                    '30' => '已发货待收货',
                ]
            ]
        ];
        return $status[$updateType][$oldStatus][$newStatus] ?? '错误';
    }
}